package org.microsites.msg;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
import org.microsites.domain.model.User;
import org.microsites.util.UserContext;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MessageDispatcherServlet extends WebSocketServlet {

    private static final long serialVersionUID = 6623299957429689925L;
    
    private final ConcurrentHashMap<String, WebSocket> members = new ConcurrentHashMap<String, WebSocket>();
    private final ConcurrentHashMap<String, CopyOnWriteArraySet<String>> rooms = new ConcurrentHashMap<String, CopyOnWriteArraySet<String>>();

    private MessageBroker msgBroker;
    
    @Override
    public void init() throws ServletException {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        if (ctx != null) {
            AutowireCapableBeanFactory bf = ctx.getAutowireCapableBeanFactory();
            if (bf != null) {
                bf.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
            }
        }

        super.init();
    }

    @Override
    protected WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
        return new Peer(userCtx.getUser());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException {
        getServletContext().getNamedDispatcher("default").forward(request,response);
    }
}
